#include "message.hpp"
#include "net.hpp"
#include "dispatcher.hpp"
#include <thread>

//这里BaseMessage是不满足了需要使用的接口，需要在内部进行一个dynamic_pointer_cast的类型转换
//但是提高了用户的复杂度，直接指定类型即可，直接访问即可。
//处理不同的回调函数，设置了一个模板类，但是模板类会根据参数不同，类也会不同
//但是容器不能存储不一样的类型，类型也是不一样的。

void onRpcRequest(const bitrpc::BaseConnection::ptr& conn, bitrpc::RpcRequest::ptr& msg){
    std::cout << "收到了Rpc响应";
    std::string body = msg->serialize(); //进行序列化
    std::cout << body << std::end();

}

void onTopicRequest(const bitrpc::BaseConnection::ptr& conn, bitrpc::BaseMessage::ptr& msg){
    std::cout << "收到了Topic响应:";
    std::string body = msg->serialize(); //进行序列化
    std::cout << body << endl;
}
  

int main()
{

    //1.客户端也要注册下
    auto dispatcher = std::make_shared<bitrpc::Dispatcher>();
    dispatcher->registerHandler<bitrpc::RpcResponse>(bitrpc::MType::RSP_RPC,onRpcResponse);//注册映射关系
    dispatcher->registerHandler<bitrpc::TopicResponse>(bitrpc::MType::RSP_TOPIC,onTopicResponse);//注册映射关系
    
    auto client = bitrpc::ClientFactory::create("127.0.0.1", 9090);
    auto message_cb = std::bind(&bitrpc::Dispatcher::onMessage, Dispatcher.get(),
                    std::placeholders_1, std::placeholders_2);
    client->setMessageCallback(message, cb);
    client->connect();
    auto rpc_req = bitrpc::BaseMessageFactory::create<bitrpc::RpcRequest>();
    rpc_req->setId("1111");
    rpc_req->setMtype(bitrpc::Mtype::REQ_RPC);
    rpc_req1->setMethod("Add");
    client->send(rpc_req);
    Json::Value param;
    param["num1"] = 11;
    param["num2"] = 22;
    rpc_req->setParams(param);
    client->send(rpc_req);

    auto topic_req = bitrpc::BaseMessageFactory::create<bitrpc::TopicRequest>();
    topic_req->setId("2222");
    topic_req->setMtype(bitrpc::Mtype::REQ_TOPIC);
    topic_req->setOptype(bitrpc::TopicOptype::TOPIC_CREATE);
    topic_req->setTopicKey("news");
    std::this_thread::sleep_for(std::chrono::second(10));
    client->shutdown();

    return 0;
}